package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogParser;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@Component
@Qualifier("LogParserWithLoopCxyImpl")
public class LogParserWithLoopCxyImpl implements LogParser {

    @Override
    public Map<String, List<LogItem>> parse(String folderName) {
        Map<String, List<LogItem>> resultMap = new HashMap<>();
        processDirectory(new File(folderName), resultMap);
        return resultMap;
    }

    private void processDirectory(File directory, Map<String, List<LogItem>> resultMap) {
        File[] files = directory.listFiles();
        LogItemParserCxyImpl logItemParser = new LogItemParserCxyImpl();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    processDirectory(file, resultMap);
                } else if (file.getName().endsWith(".log")) {
                    try {
                        List<LogItem> logItems = parseLogFile(file.getAbsolutePath(), logItemParser);
                        resultMap.put(file.getAbsolutePath(), logItems);
                    } catch (IOException e) {
                        // 处理异常
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private List<LogItem> parseLogFile(String filePath, LogItemParserCxyImpl logItemParser) throws IOException {
        List<LogItem> logItems = new ArrayList<>();
        List<String> lines = Files.readAllLines(Paths.get(filePath));

        for (String line : lines) {
            Optional<LogItem> parsedLogItem = logItemParser.parse(line);
            parsedLogItem.ifPresent(logItems::add);
        }
        return logItems;
    }


}
